package work.lianbiao;

import work.ListNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Problem21 {

    //指针法
    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        ListNode first = new ListNode(1);
        ListNode asd = first;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                asd.next = list1;
                list1 = list1.next;
            } else {
                asd.next = list2;
                list2 = list2.next;
            }
            asd = asd.next;
        }
        if (list1 == null) {
            asd.next = list2;
        } else {
            asd.next = list1;
        }
        ListNode.printList(first.next);
        return first.next;
    }

    //递归法

    public static void main(String[] args) {
        int[] a = {1, 2, 4};
        int[] b = {1, 3, 4};
        ListNode node = ListNode.listNodeFromArray(a);
        ListNode node1 = ListNode.listNodeFromArray(b);
        Problem21 problem21 = new Problem21();
        problem21.mergeTwoLists(node, node1);
    }

    //
    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        } else if (list1.val < list2.val) {
            list1.next = mergeTwoLists1(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists1(list1, list2.next);
            return list2;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        else if (list2 == null)return list1;
        if (list1.val < list2.val) {
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        }
        else{
            list2.next = mergeTwoLists(list2.next, list1);
            return list2;
        }
    }


}
